package controller;

import entity.User;
import service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;

@Controller
public class LoginController {
    @Autowired
    private UserService userService;

    @GetMapping("/login")
    public String showLoginForm() {
        return "index";
    }


@PostMapping("/login")
public String login(HttpServletRequest request,
                    @RequestParam String username, @RequestParam String password, Model model) {
    User user = userService.findByUsername(username);
//    boolean isvalid = true;
    if (user != null && user.getPassword().equals(password)) {
        request.getSession().setAttribute("user", user);

        if (user.getRole().equals(200)) {
            return "redirect:/order";
        } else {
            return "redirect:/order_user";
        }
    } else {
        model.addAttribute("error", "Invalid username or password");
        return "redirect:/login";
    }
}
}
